<template>
    <div>
        <h1>ref watch</h1>
        <p>{{count}} <button @click="handleClick">add</button></p>
        <p>{{fristname}}{{lastname}}</p>
        <h1>reactive watch</h1>
        <p>{{watchA}}  | <button @click="AddA">addA</button></p>
        <p>{{watchC}}  |  <button @click="rename">编辑</button></p>
        <ul>
            <li v-for="(item,index) in numbers" :key=index>{{item}}</li>
        </ul>
        <h1>wacth obj</h1>
        <p>{{person.name}}{{person.age}}</p>
    </div>
</template>
<script>
import {defineComponent,ref, reactive, toRefs,watch, watchEffect} from 'vue'
import _ from 'loadsh'
export default defineComponent ({
    setup () {
        const count = ref(0)
        const fristname = ref('')
        const lastname = ref('')
        const state = reactive({
            watchA: 1,
            watchB: 2,
            watchC: 'lxy',
            AddA: () => state.watchA++,
            rename: () => state.watchC = state.watchA.toString() + state.watchB.toString()
        })
        
        const numbers = reactive([1,2,3,4,5])

        const obj = reactive({
            person: {
                name: 'xyl',
                age: 18
            }
        })
        
        const handleClick = () => {
            count.value++
        }
        
       // 可在页面初始化加载的时候就自动执行，可返回一个stop 手动结束监听
       // 但和watch 相比，目前暂时没有发现有什么用处 
       const stop = watchEffect(() => console.log(count.value))

        setTimeout(() => {
          count.value++ 
        },1000)
        
        stop()

        // 注意 监听ref和reactive是有区别的
        // wacth reactive 某一项的时候，需要() => return ()
        watch(count,(val,prev) => {
          console.log('old' + prev)
          console.log('new' + val)
        })

        //watch 多个ref 值 
        watch([fristname,lastname],(val,prev) => {
            console.log(val,prev)
        })

        fristname.value = 'lxy'
        lastname.value = 'hahahhaah'

        // wacth reactive 数组 使用ts的时候报错，注意
        watch(() => [...numbers], (val,prev) => {
           console.log(val,prev)
        })

        numbers.push(6)

        // wacth reactive obj
        watch(() => _.cloneDeep(obj), (val,prev) => {
            console.log(val.person.name,prev.person.name)
        },{deep: true})
        obj.person.name = 'lxy'
        obj.person.age = 20
        // 监听整个数据
        // watch (state, (val,oldV) => {
        //    console.log(val,oldV)
        // })

        // 监听某一个
        // watch ( () => state.watchA, (val,prev) => {
        //    console.log(val)
        //    console.log(prev)
        // })
        
        // 监听多个数据
        watch(() => [state.watchA,state.watchC], (val,prev) => {
            console.log(val)
            console.log(prev)
        })
        const data = toRefs(state)  
        return {
            count,
            fristname,
            lastname,
            ...data,
            ...toRefs(obj),
            numbers,
            handleClick
        }
    }
})
</script>